package camuyen.ltwlibrary.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import camuyen.ltwlibrary.model.Author;
import camuyen.ltwlibrary.util.HibernateUtil;

public class AuthorDao {
	public static Author getAuthor(Long authorId) {
        Session session = HibernateUtil.openSession();
        Author author = (Author) session.load(Author.class, authorId);
        return author;
    }

    public static void saveAuthor(Author author) {
        Session session = HibernateUtil.openSession();
        session.getTransaction().begin();
        session.save(author);
        session.getTransaction().commit();
        session.close();
    }
    
    public static void updateAuthor(Author author) {
        Session session = HibernateUtil.openSession();
        session.getTransaction().begin();
        session.update(author);
        session.getTransaction().commit();
        session.close();
    }
    
    public static List<Author> getAll() {
    	Session session = HibernateUtil.openSession();
    	Query query = session.createQuery("SELECT aut FROM Author aut");
    	List<Author> allAuthor = (List<Author>) query.list();
        session.close();
    	return allAuthor;
    }

    public static List<Author> getAuthorsByListId(List<Long> listId) {
        List<Author> listAuthor = new ArrayList<Author>();
        for (Long id: listId) {
            listAuthor.add(AuthorDao.getAuthor(id));
        }

        return listAuthor;
    }
}
